package com.easy.goods.controller;

import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.easy.bean.Products;
import com.easy.goods.mapper.ESRepository;

@RestController
public class Es {
    @Autowired
    ESRepository esRepository;
    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;
    @RequestMapping( "test")
public Object test(){
   Iterable<Products> iterable = esRepository.findAll();
   for (Object o : iterable){
       System.out.println(o);
   }
        System.out.println("===========================================================================");
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                // 查询条件
                .withQuery(QueryBuilders.queryStringQuery("手机").defaultField("name"))
                // 分页
                .withPageable(PageRequest.of(0, 10))
                // 高亮字段显示
                .withHighlightFields(new HighlightBuilder.Field("name")).build();
        SearchHits<Products> sh = elasticsearchRestTemplate.search(nativeSearchQuery, Products.class);
        for (SearchHit<Products> user : sh) {
            System.out.println(user);
        }
   return iterable;
}


}
